package controllers

import (
	"fmt"
	"net/http"

	"github.com/saint-yellow/go-pl/toys/goblog/app/models/article"
	"github.com/saint-yellow/go-pl/toys/goblog/app/models/category"
	"github.com/saint-yellow/go-pl/toys/goblog/app/requests"
	"github.com/saint-yellow/go-pl/toys/goblog/pkg/flash"
	"github.com/saint-yellow/go-pl/toys/goblog/pkg/route"
	"github.com/saint-yellow/go-pl/toys/goblog/pkg/view"
)

// CategoriesController 文章分类控制器
type CategoriesController struct {
    BaseController
}

// Create 文章分类创建页面
func (*CategoriesController) Create(w http.ResponseWriter, r *http.Request) {
    // 1. 初始化数据
    _category := category.Category{
        Name: r.PostFormValue("name"),
    }

    // 2. 表单验证
    errors := requests.ValidateCategoryForm(_category)

    // 3. 检测错误
    if len(errors) == 0 {
        // 创建文章分类
        _category.Create()
        if _category.ID > 0 {
            fmt.Fprint(w, "创建成功！")
            // indexURL := route.Name2URL("categories.show", "id", _category.GetStringID())
            // http.Redirect(w, r, indexURL, http.StatusFound)
        } else {
            w.WriteHeader(http.StatusInternalServerError)
            fmt.Fprint(w, "创建文章分类失败，请联系管理员")
        }
    } else {
        view.Render(w, view.D{
            "Category": _category,
            "Errors":   errors,
        }, "categories.create")
    }
}

// Store 保存文章分类
func (*CategoriesController) Store(w http.ResponseWriter, r *http.Request) {
	// 1. 初始化数据
    _category := category.Category{
        Name: r.PostFormValue("name"),
    }

    // 2. 表单验证
    errors := requests.ValidateCategoryForm(_category)

    // 3. 检测错误
    if len(errors) == 0 {
        // 创建文章分类
        _category.Create()
        if _category.ID > 0 {
            flash.Success("分类创建成功")
            indexURL := route.NameToURL("articles.index")
            http.Redirect(w, r, indexURL, http.StatusFound)
        } else {
            w.WriteHeader(http.StatusInternalServerError)
            fmt.Fprint(w, "创建文章分类失败，请联系管理员")
        }
    } else {
        view.Render(w, view.D{
            "Category": _category,
            "Errors":   errors,
        }, "categories.create")
    }
}

// Show 显示分类下的文章列表
func (cc *CategoriesController) Show(w http.ResponseWriter, r *http.Request) {
    // 1. 获取 URL 参数
    id := route.GetRouteVariable("id", r)

    // 2. 读取对应的数据
    _category, err := category.Get(id)

    // 3. 获取结果集
    articles, pagerData, err := article.GetByCategoryID(_category.GetStringID(), r, 2)

    if err != nil {
        cc.ResponseForSQLError(w, err)
    } else {

        // ---  2. 加载模板 ---
        view.Render(w, view.D{
            "Articles":  articles,
            "PagerData": pagerData,
        }, "articles.index", "articles._article_meta")
    }
}

// todo: 请为文章分类开发编辑功能，允许登录用户可以编辑某个分类
